package com.minaClient.fileHandler;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.minaClient.service.Iohandler;
import com.minaClient.utils.PropertiesUtil;

public class ClientSend {  
	Logger log=Logger.getLogger(ClientSend.class.getName());
	 NioSocketConnector connector ;
	 IoSession session = null;  
     ConnectFuture future=null;
  public ClientSend(){ 
	  
  }  
  public void connect(String flie) throws InterruptedException{  
      connector = new NioSocketConnector();  
        
      ObjectSerializationCodecFactory factory = new ObjectSerializationCodecFactory();    
      factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);    
      factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);    

      // Configure the service.  
      connector.setConnectTimeoutMillis(50*1000);  
      //connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(factory));  
      connector.getFilterChain().addLast("logger", new LoggingFilter());  

      connector.setHandler(new SendStreamIoHandler(flie));  
        

     
	  try { 
	      for (;;) {  
	          
	              future = connector.connect(new InetSocketAddress(PropertiesUtil.CLIENT_SEND_HOST,PropertiesUtil.RECIVE_SEND_PORT));  
	              future.awaitUninterruptibly();  
	              session = future.getSession();
	              break;  
	       
	      } 
	     
	      
      } catch (RuntimeIoException e) {  
    	  log.debug("发生异常 Failed to connect."+PropertiesUtil.CLIENT_SEND_HOST+"?"+PropertiesUtil.RECIVE_SEND_PORT);

          System.err.println("Failed to connect.");  
          e.printStackTrace();  
      }  

 
  }  
  public void closed() {
	  log.debug("发送完毕自动关闭");
	  connector.dispose();  
	     // wait until the summation is done  
	  if(session!=null) {
		  session.closeNow();
		  session.getCloseFuture().awaitUninterruptibly();    
	  }
	  if(future!=null) {
		  future.cancel();
	  }
  }

  /** 
   * @param args 
   * @throws InterruptedException  
   */  
  public static void main(String[] args) throws InterruptedException {  
      ClientSend client = new ClientSend();  
      client.connect("C:\\Users\\Administrator\\Desktop\\123.txt");  
  }  

}  